<template>
<div class="message-container">
    <div class="title-box">
        <div class="title-text">消息列表</div>
        <div class="title-right"><img :src="ePic" alt=""></div>
    </div>
    <div class="message-box" v-for="(item,index) in isSentAdviserList" @click="goChat(item)">
        <div class="head-box">
            <div class="newRed" v-if="item.hasNewMsg>0">{{item.hasNewMsg}}</div>
            <img v-if="item.head_portrait" :src="item.head_portrait" alt="">
            <img v-else :src="serverUrl+'im/Avatar_male.png'" alt="">
        </div>
        <div class="message-right-box">
            <div class="message-right-top">
                <div class="name">{{item.name}}</div>
                <div class="last-message-time">{{item.MsgTimeStamp|formatTime}}</div>
            </div>
            <div class="message-right-bottom">
                <!--<div class="message-text">-->
                    <!--<span v-if="!item.lastMessage.content.type">{{item.lastMessage.content}}</span>-->
                    <!--<span v-if="item.lastMessage.content.type==204">[PDF文件]</span>-->
                    <!--<span v-if="item.lastMessage.content.type==506">[视频]</span>-->
                    <!--<span v-if="item.lastMessage.content.type==507">[链接]</span>-->
                    <!--<span v-if="item.lastMessage.content.type==508">[链接]</span>-->
                    <!--<span v-if="item.lastMessage.content.type==509">[图片]</span>-->
                <!--</div>-->
                <div class="message-text">{{item.MsgShow|textChange}}</div>
            </div>

        </div>
    </div>
    <div class="more-adviser" @click="goAdviserList()">
        <img :src="serverUrl+'im/more-adviser.png'" alt="">
    </div>
    <loading v-if="loading"></loading>
</div>
</template>

<script>
    import ubt from '@/utils/ubt.js'
    import {imService} from '@/services'
    import Loading from '@/components/loading.vue'
    import util from '@/utils/util.js'
    var tls = require('../../utils/im/tls.js')
    var webim = require('../../utils/im/webim.js')

    var webimhandler = require('../../utils/im/webim_handler.js')
    export default {
        data() {
            var serverUrl="http://skyforest.static.elab-plus.com/";
            return {
                title:'在线咨询',
                adviserList:[],
                loading:false,
                houseid:'109',
                serverUrl:serverUrl,
                houseid:'109',
                pathName:{},
                closeButton:`${serverUrl}im/close-button.png`,
                isSentAdviserList:[],
                ePic:`${serverUrl}im/e-pic.png`,
                localCustomerId:null,
                Config:{
                    sdkappid: 1400091043,
                    accountType: 26432,
                    accountMode: 0 //帐号模式，0-表示独立模式，1-表示托管模式
                },
                userInfo: {nickName:localStorage.getItem('tmpMobile')||'web用户'},
            }
        },
        filters:{
          formatTime(val){
              return util.formatTodayTime(new Date(val*1000))
          },
            textChange(val){
              console.log(val,'iiiii')
              if(val.includes('csyzwfelab20180425hhhdfq')){
                  let newVal = JSON.parse(val);
                  if(newVal.type==506){
                      return '视频'
                  }else if(newVal.type==507){
                      return 'H5'
                  }
                  else if(newVal.type==508||newVal.type==513){
                      return ''
                  }
                  else if(newVal.type==102){
                      return ''
                  }
                  else if(newVal.type==515||newVal.type==516){
                      return newVal.param.text
                  }
                  else if(newVal.type==104){
                      return ''
                  }
                  else if(newVal.type==509){
                      return '图片'
                  }
                  else if(newVal.type==502){
                      return ''
                  }
                  else if(newVal.type==204){
                      return 'PDF'
                  }else{
                          return ''
                  }
              }else if(val.includes('【系统消息】')||val.includes('【系统提示】')){
                      return ''
                  }
                  else if(val.includes('onChangePlay')){
                  return ''
              }else if(val.includes('视频通话')){
                  return ''
              }else if(val.includes('e看房已发送')){
                  return ''
              }
              else{
                  return val
              }

            }
        },
        components: {
            Loading
        },
        created(){
            if(this.$route.query&&this.$route.query.houseid==102){
                this.Config.sdkappid = 1400075851;
                this.Config.accountType = 24512;
                this.houseid = this.$route.query.houseid;
                sessionStorage.setItem('imhouseid',this.$route.query.houseid)
            }
        },
        mounted() {
            util.setTitle(this.title)
             if (/(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent)) {
                 window.addEventListener("popstate", function(e) {
                console.log("后退");
                self.location.reload();
            }, false);
            var state = {
                title : "",
                url : "#"
            };
            window.history.replaceState(state, "", "");
                var isPageHide = false;
                window.addEventListener('pageshow', function () {
                    if (isPageHide) {
                        window.location.reload();
                    }
                });
                window.addEventListener('pagehide', function () {
                    isPageHide = true;
                });
            }
            if(this.$route.query&&this.$route.query.pathName){
                console.log(this.$route.query,'grgrg')
                this.$store.dispatch('setPathName',this.$route.query);
            }
            this.localCustomerId = localStorage.getItem('localCustomerId'+this.houseid);
            if(!(this.localCustomerId&&localStorage.getItem(this.localCustomerId+'&isSendMsg'+this.houseid))){
                this.$router.push({path:'./adviserList',query:this.$store.state.pathName})
                return
            }
            this.login();
            // this.getHistoryMsgs();
            // this.isSentAdviserList = JSON.parse(localStorage.getItem(this.localCustomerId+'$messageArr'))||[];
            // console.log(JSON.parse(localStorage.getItem(this.localCustomerId+'$messageArr')))
            // console.log(this.isSentAdviserList,'gegege')
        },
        methods: {
            goAdviserList(){
                console.log(this.$store.state.pathName,'hgggggggggg')
                ubt.trackEvent('01011091','sfc.nb.app.home.videoshow.adviserList.more.click','','','','click')
              this.$router.push({path:'./adviserList',query:this.$store.state.pathName})
            },
             goChat(item){
                if(!(item.id&&item.houseid&&item.tel)){
                    this.$message('数据有误，找不到'+item.To_Account)
                    return
                }
                sessionStorage.setItem('adviserInfo',JSON.stringify(item))
                this.$router.push({name:'im',query:this.$route.query})
            },
            async login(){
                this.loading = true;
                var that = this;
                let result = await imService.getUserSig(util.reformParam(util.accountUrl,{identifier: this.localCustomerId, appId:that.Config.sdkappid}))
                webimhandler.init({
                    accountMode:this.Config.accountMode
                    , accountType: this.Config.accountType
                    , sdkAppID: this.Config.sdkappid
                    , selType: webim.SESSION_TYPE.C2C
                    , selSess: null //当前聊天会话
                });

                var loginInfo = {
                    'sdkAppID': this.Config.sdkappid, //用户所属应用id,必填
                    'appIDAt3rd': this.Config.sdkappid, //用户所属应用id，必填
                    'accountType': this.Config.accountType, //用户所属应用帐号类型，必填
                    'identifier': result.data.single.identifier, //当前用户ID,必须是否字符串类型，选填
                    'identifierNick': this.userInfo.nickName, //当前用户昵称，选填
                    'userSig': result.data.single.signature, //当前用户身份凭证，必须是字符串类型，选填
                };
                var listeners = {

                    "onConnNotify": webimhandler.onConnNotify, //选填
                    "onBigGroupMsgNotify": function (msg) {
                        webimhandler.onBigGroupMsgNotify(msg, function (msgs) {
                        })
                    }, //监听新消息(大群)事件，必填
                    "onMsgNotify": function (msg) {
                        webimhandler.onMsgNotify(msg, function (msgs) {
                            console.log(msgs,'ppppppp')
                            var msg = '【系统消息】该用户当前登录方式为web登录，无法使用此功能';
                            //debugger
                            if(msgs.content&&msgs.content.type==102||msgs.content.type==508||msgs.content.type==512||msgs.content.type==104){
                                webimhandler.onSendMsg(msg,msgs.fromAccountNick);
                                return
                            }else if(msgs.content&&msgs.content.type==502){
                                if(msgs.content.param.isShowInvitation===true||msgs.content.param.isShowInvitation==='true'){
                                    console.log(msgs.content,'ppp')
                                    return
                                }else{
                                    console.log('go')
                                    webimhandler.onSendMsg(msg,msgs.fromAccountNick);
                                    return
                                }
                            }
                            else if(msgs.content&&msgs.content.type==513){

                                return
                            }
                            else if(msgs.content&&(typeof msgs.content=='string')&&msgs.content.includes('onChangePlayAudio')){
                                webimhandler.onSendMsg(msg,msgs.fromAccountNick);
                                return
                            }
                            else{
                                that.addNewMsg(msgs)
                            }

                        })
                    },//监听新消息(私聊(包括普通消息和全员推送消息)，普通群(非直播聊天室)消息)事件，必填
                    "onGroupSystemNotifys": webimhandler.onGroupSystemNotifys, //监听（多终端同步）群系统消息事件，必填
                    "onGroupInfoChangeNotify": webimhandler.onGroupInfoChangeNotify//监听群资料变化事件，选填
                };
                var options = {
                    'isAccessFormalEnv': true,//是否访问正式环境，默认访问正式，选填
                    'isLogOn': false//是否开启控制台打印日志,默认开启，选填
                };
                webimhandler.sdkLogin(loginInfo, listeners, options,function(){
                    that.getHistoryMsgs();
                });
            },
            addNewMsg(msg){
               let newMsg = msg;
               console.log(newMsg,'new',this.adviserList)

                for(let i = 0;i<this.adviserList.length;i++){
                    if(this.adviserList[i].userId ==msg.fromAccountNick.substring(0,msg.fromAccountNick.indexOf('_'))){
                        newMsg = Object.assign(this.adviserList[i],msg);
                        console.log(newMsg,'加最新消息了')

                    }
                }
                console.log(this.isSentAdviserList,newMsg,'iopkojo')

                let flag = false
                for(let j = 0;j<this.isSentAdviserList.length;j++){
                    if(newMsg.userId==this.isSentAdviserList[j].userId){
                        console.log('即将崛起', typeof newMsg.content)
                        flag = true;
                        this.isSentAdviserList[j].hasNewMsg++;
                        if(
                            typeof newMsg.content=='object'
                        ){

                            this.isSentAdviserList[j].MsgShow = JSON.stringify(newMsg.content);
                        }else{
                            this.isSentAdviserList[j].MsgShow = newMsg.content;

                        }
                        this.isSentAdviserList[j].MsgTimeStamp =Math.floor(new Date().getTime()/1000);
                        return
                    }
                }
                if(!flag){
                    newMsg.hasNewMsg = 1;
                    this.isSentAdviserList.unshift(newMsg);
                }
            },
            getHistoryMsg(){

                let that = this
                webim.getRecentContactList({
                    'Count': 100 //最近的会话数 ,最大为 100
                },function(resp){
                    console.log(resp,'yy')
                    if(resp.SessionItem.length>0){
                        for(var i =0;i<resp.SessionItem.length;i++){
                            console.log(resp,'yyyyyy')
                            for(var j = 0;j<that.adviserList.length;j++){
                                var outData = resp.SessionItem[i].To_Account;
                                if(outData.substring(0,outData.indexOf('_'))==that.adviserList[j].userId){
                                    resp.SessionItem[i] = Object.assign(resp.SessionItem[i],that.adviserList[j])
                                }
                            }
                        }
                    }else{
                        this.$message('暂无最新消息')
                    }
                    that.isSentAdviserList =resp.SessionItem;
                    that.loading = false;
                    //业务处理
                },function(resp){
                    setTimeout(()=>{
                        that.getHistoryMsg();
                    },1000)
                    console.log(resp,'gggg')
                    //错误回调
                });
            },
             async getHistoryMsgs(){
                this.loading = true;
                setTimeout(()=>{
                    this.loading = false
                },4000)
                var that = this;
                 let time = util.formatDatetime(new Date())
                 let result = await imService.getAllAdviserList({
                     houseid:that.houseid,
                     time:time,
                     pageNo:1,
                     pageSize:100
                 })
                 console.log(result,'tryutu')
                 if(result){
                     this.adviserList = result.data.pageModel.resultSet||[];
                 }
                 this.adviserList.forEach((item)=>{
                     item.hasNewMsg = 0;
                 })
                setTimeout(()=>{
                   that.getHistoryMsg()
                },200)

            }
        }
    }
</script>

<style lang="scss" scoped>
  .message-container{
      font-size: 16px;
      .title-box{
          width:100%;
          height:70px;
          display:flex;
          box-sizing: border-box;
          padding:10px 20px 10px 20px;
          justify-content: space-between;
          align-items: center;
          .title-text{
              line-height: 50px;
            font-size:32px;
            font-weight:bold;
            height:50px;
          }
          .title-right{
            height:35px;
              width:50px;
              overflow: hidden;
              img{
                  width:100%;
                  height:100%;
              }
          }
      }
      .message-box{
          border-bottom:1px solid #cccccc;
          box-sizing: border-box;
          margin-left:20px;
          width:calc(100% - 20px);
          height:80px;
          display:flex;
          padding-right:20px;
          align-items: center;
          justify-content: flex-start;
          .head-box{
              position: relative;
              .newRed{
                  z-index:20;
                  width:15px;
                  height:15px;
                  color:#fff;
                  top:2px;
                  right:4px;
                  font-size:14px;
                  border-radius: 50%;
                  background: red;
                  text-align: center;
                  line-height: 15px;
                  position:absolute;
              }
              width:60px;
              height:60px;
              overflow: hidden;
              img{
                  border-radius:50%;
                  width:100%;
                  height:100%;
              }
          }
          .message-right-box{
              flex:1;
              .message-right-top{
                  display:flex;
                  justify-content: space-between;
                  .last-message-time{
                      color:#999999;
                  }
                  .name{
                      margin-left:10px;
                      font-weight: bold;
                  }
              }
              .message-right-bottom{
                  .message-text{
                      text-overflow: ellipsis;
                      white-space:nowrap;
                      overflow: hidden;
                      width:250px;
                  }
                  margin-left: 10px;
                  color:#999999;
              }

          }

      }
      .more-adviser{
         height:60px;
          width:calc(100% - 20px);
          display:flex;
          align-items: center;
          margin-left:20px;
          justify-content: center;
          border-bottom: 1px solid #cccccc;
          img{
              height:20px;
              /*margin:0 auto;*/
          }
      }

  }
</style>
